<template>
  <div class="editor—wrapper w-full">
    <Toolbar
      :editor="editorRef"
      :default-config="toolbarConfig"
      :mode="editorMode"
      class="toolbar-container"
    />
    <Editor
      :default-config="editorConfig"
      :mode="editorMode"
      v-model="defaultHtml"
      class="editor-container"
      @on-change="handleChange"
      @on-created="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
  import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'

  import { getToken } from '#/utils/auth'
  import { useVModel } from '@vueuse/core'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { ElMessage } from 'element-plus'

  const props = withDefaults(
    defineProps<{
      editorMode?: string
      imageUploadUrl: string
      modelValue?: string
    }>(),
    {
      modelValue: '',
      editorMode: 'default', // 编辑器模式: default, simple
    }
  )
  const emits = defineEmits(['update:modelValue'])

  const defaultHtml = useVModel(props, 'modelValue', emits)
  const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
  const toolbarConfig: Partial<IToolbarConfig> = {
    // 排除不需要的菜单
    excludeKeys: ['insertVideo', 'group-video', 'emotion', 'codeBlock', 'todo', 'fullScreen'], // 'fullScreen', 'group-video'
  }

  const uploadImageConfig = {
    server: import.meta.env.VITE_APP_BASE_API + props.imageUploadUrl,
    fieldName: 'image',
    timeout: 30 * 1000, // 30s
    maxFileSize: 10 * 1024 * 1024, // 10M
    maxNumberOfFiles: 10, // 最多可上传 10 个
    base64LimitSize: 5 * 1024, // 小于该值就插入 base64 格式（不上传）
    headers: { Authorization: `Bearer ${getToken()}` },
    onBeforeUpload(file: File) {
      // file 选中的文件，格式如 { key: file }
      return file
      // 可以 return
      // 1. return file 或者 new 一个 file ，接下来将上传
      // 2. return false ，不上传这个 file
    },
    onProgress(progress: number) {
      console.log('progress', progress)
    },
    onSuccess(file: File, res: any) {
      console.log(`${file.name} 上传成功`, res)
    },
    onFailed(file: File, res: any) {
      console.log(`${file.name} 上传失败`, res)
    },
    onError(file: File, err: any, res: any) {
      console.log(`${file.name} 上传出错`, err, res)
      if (err.request.status == 403) {
        ElMessage.error('没有权限进行该操作')
      } else if (err.request.status == 413) {
        ElMessage.error('文件太大，先压缩文件体积再尝试')
      }
    },
  }

  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: uploadImageConfig,
    },
  }

  const handleCreated = (editor: IDomEditor) => {
    editorRef.value = editor
  }
  function handleChange(editor: IDomEditor) {
    emits('update:modelValue', editor.getHtml())
  }

  // 使用 useVModel ，不用写 watch
  // watch(
  //   () => props.modelValue,
  //   (newV) => {
  //     defaultHtml.value = newV
  //     //editor.setHtml(newV)
  //     // console.log('editor defaultHtml.value', newV)
  //   },
  //   {
  //     immediate: true,
  //   }
  // )

  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
  .editor—wrapper {
    border: 1px solid #e4e7ed;
    //border-radius: 5px;
  }

  .toolbar-container {
    border-bottom: 1px solid #e4e7ed;
    border-radius: 5px 5px 0 0;

    .w-e-bar {
      border-radius: 5px !important;
    }
  }

  .editor-container {
    height: 600px !important;
    overflow-y: hidden;
    border-radius: 5px;

    .w-e-scroll {
      border-radius: 5px !important;
    }
  }
</style>
